package com.liachen.stock.ext.impl;

import com.alibaba.fastjson.JSONObject;
import com.liachen.common.constant.Constant;
import com.liachen.stock.entity.StockSimple;
import com.liachen.stock.entity.StockSummaryInfo;
import com.liachen.stock.ext.KLineApiService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * TODO 功能描述
 *
 * @author chen.liang
 * @date 2020/2/22 22:45
 * @since V1.0
 */
@Service
public class KLineApiServiceImpl implements KLineApiService {
    private static final String K_LINE_API_STOCK_INFO = "http://kline.api.shqingsi.cn/v1/quotes.php?code=%s";
    @Override
    public StockSimple getStockTodayInfo(StockSummaryInfo stockSummaryInfo) throws IOException {
        String code = stockSummaryInfo.getCode().startsWith("6") || stockSummaryInfo.getCode().startsWith("5") ? "sh" + stockSummaryInfo.getCode() : "sz" + stockSummaryInfo.getCode();
        Document doc = Jsoup.connect(String.format(K_LINE_API_STOCK_INFO, code)).ignoreContentType(true).userAgent(Constant.USER_AGENT).get();
        JSONObject result = JSONObject.parseObject(doc.text());
        BigDecimal lastPrice = result.getJSONArray("data").getJSONObject(0).getBigDecimal("closePrice");
        BigDecimal price = result.getJSONArray("data").getJSONObject(0).getBigDecimal("price");
        BigDecimal todayIncrease = price.add(lastPrice.negate()).multiply(BigDecimal.valueOf(100)).divide(lastPrice, 2, BigDecimal.ROUND_HALF_UP);
        StockSimple stockSimple = new StockSimple();
        stockSimple.setCode(stockSummaryInfo.getCode());
        stockSimple.setName(stockSummaryInfo.getName());
        stockSimple.setIncrease(todayIncrease);
        return stockSimple;
    }

}
